﻿using JyFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

namespace JyFramework
{ 
    public class RefController
    {
        #region singleton
        public static RefController Ins { get { return _ins; } }
        public static void CreateIns() { if (_ins == null) _ins = new RefController(); }
        private static RefController _ins;
        private RefController() { Init(); }
        #endregion

        public static string OnAddRef = "OnAddRef";
        public static string OnReduceRef = "OnReduceRef";    
        
        /// <summary>
        ///  生成obj的时候,需要添加到管理中
        ///  这里不做引用增加
        /// </summary>
        /// <param name="resName"></param>
        /// <param name="refObj"></param>
        public void AddRefObj(string resName, RefAssetBundle refAb)
        {
            RefAssetBundle temp = null;

            if (_refObjs.TryGetValue(resName, out temp))
            {
                _refObjs[resName] = refAb;
            }
            else
            {
                _refObjs.Add(resName, refAb);
            }
        }
            

        private Dictionary<string, RefAssetBundle> _refObjs;

        private void Init()
        {
            _refObjs = new Dictionary<string, RefAssetBundle>();
            MessageManager.Ins.RegistEvent(OnAddRef, OnAddRefCallBack);
            MessageManager.Ins.RegistEvent(OnReduceRef, OnReduceRefCallBack);
        }

        /// <summary>
        /// 只有添加了引用计数脚本后才做引用计数
        /// </summary>
        /// <param name="args"></param>
        private void OnAddRefCallBack(object[] args)
        {
            string resName = (string)args[0];

            RefAssetBundle refObj = null;
            if (_refObjs.TryGetValue(resName, out refObj))
                refObj.RefCount += 1;
            else
            {
                Debug.Log(string.Format("无路径为： <{0}> 的资源！", resName));
            }
        }

        /// <summary>
        /// 引用减少
        /// </summary>
        /// <param name="args"></param>
        private void OnReduceRefCallBack(object[] args)
        {
            string resName = (string)args[0];

            RefAssetBundle refObj = null;
            if (_refObjs.TryGetValue(resName, out refObj))
            {
                refObj.RefCount -= 1;
                if(refObj.RefCount <= 0)
                {
                    refObj.ClearSelf();
                    _refObjs.Remove(resName);
                }
            }

        }


    }
}
